var hosturl = "https://bab.moreqifu.cn";
var requestData = {};
var nowtimestamp = "";

$(document).ready(function(){
    nowtimestamp = Math.round(new Date().getTime()/1000).toString();
    if (ttwlLink.type == "dycard") {
        var douyin = isDouyinClient();
        if (douyin) {
            if (ttwlLink.status == "create") {
                localStorage.setItem('mini_set',1);
                var currentUrl = window.location.href;
                currentUrl = currentUrl.replace('?status=create', '');
                currentUrl = currentUrl.replace('&status=create', '');
                window.location.href = currentUrl;
                return;
            }
            var mini_settimes = localStorage.getItem('mini_set') || 2;
            if (mini_settimes == 1) {
                localStorage.setItem('mini_set',3);
                var device = getDeviceType();
                if (device == "android") {
                    $("#public-web-container").prepend("<p class='create-notice'>抖音私信卡片首次必须使用苹果手机制作,制作成功后安卓和苹果手机均可分享转发。</p>");
                    setTimeout(function() {
                        preRequestData();
                    },3000);
                } else {
                    $("body").css({"background-color":"#000000"});
                    $("#public-web-container").html('<img src="https://res.wailian1.cn/uploads/20230824/9089278.jpg" style="width:100%;"/>');
                    return;
                }
            } else {
                preRequestData();
            }
        } else {
            errorNotice();
        }
    } else {
        preRequestData();
    }
});

function errorNotice() {
    $(".weui-msg").show();
    $(".public-container").hide();
    $(".weui-msg__title").text("请使用抖音打开");
    $(".weui-msg__desc").text("本链接为抖音专用链接,请使用抖音APP访问。");
}

function preRequestData() {
    generateRecordId().then(record_id=>{
        requestDataMethod(record_id).then(reqData=>{
            requestData = reqData;
            linkListStatic();
            getUrlScheme();
        });
    });
}

function linkListStatic() {
    wailianStaticMethod(hosturl+"/api/version/1/jump/link_web_statistic",ttwlLink.links_id,requestData,true,false);
}

function getDeviceType() {
    if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
        return "iphone";
    } else if (/(Android)/i.test(navigator.userAgent)) {
        return "android";
    } else {
        return "pc";
    };
}

function isDouyinClient(){
    var ua = window.navigator.userAgent.toLowerCase();
    if(ua.match(/aweme/i) == 'aweme'){
        return true;
    } else {
        return false;
    }
}

function requestDataMethod(record_id) {
    var requestData = new Promise(function(resolve,reject){
        var leftlength = 16 - ttwlLink.links_id.length;
        if (leftlength >= 0) {
            var key = ttwlLink.links_id;
            for (var i = 0; i < leftlength; i++) {
                key += "W";
            }
        } else {
            var key = ttwlLink.links_id.slice(0,16);
        }
        var timestamp = parseInt(nowtimestamp) + 10800;
        var iv = timestamp+"WLWLWL";
        var saltstart = "wl";
        var saltend = "lw";
        var sign = CryptoJS.MD5(saltstart+iv+key+iv+saltend).toString();
        var token = CryptoJS.MD5(iv+key+iv+saltend).toString();
        var childRequestData = {"key":key,"timestamp":timestamp,"sign":sign,"token":token,"record_id":record_id}
        resolve(childRequestData)
    });
    return requestData;
}

function generateRecordId() {
    var record_id = new Promise(function(resolve,reject){
        var tableId = (new Date().getMonth()+1) % 4;
        var vertify = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        var sd = '';
        for (var i = 0; i < 6; i++) {
            var random = Math.floor(Math.random() * (vertify.length));
            sd += vertify[random];
        }
        var recordId = tableId+ttwlLink.links_id+nowtimestamp+sd;
        resolve(recordId)
    });
    return record_id;
}

function getUrlScheme() {
    var apiRequestData = {"key":requestData.key,"sign":requestData.sign,"token":requestData.token,"timestamp":requestData.timestamp,"links_id":ttwlLink.links_id,"appid":"","record_id":requestData.record_id};
    $.ajax({
        url: hosturl+"/api/version/2/jump/urlscheme_sample",
        method: "POST",
        data:apiRequestData,
        success:function(result){
            if (result.status == "success") {
                if (ttwlLink.redirectType == 1) {
                    window.location.href = result.data.urlscheme;
                    // window.location.href = '/article/'+ttwlLink.links_id;
                }
                $(".ttwl-link").attr("src",result.data.urlscheme);
            } else {
                $(".weui-msg").show();
                $(".public-container").hide();
                $(".weui-msg__title").text("链接加载失败");
                $(".weui-msg__desc").text(result.msg);
            }
        }
    });
}